import numpy as np
import cv2
from tqdm import tqdm
import os

'''
作用：
要是xml指向的图片不存在，那么就删除xml文件
xml文件要是不存在，删除对应的照片
'''

def load_annotations(path):
    with open(path) as f:
        annotations = list(filter(lambda x: len(x) > 0, f.readlines()))
    return annotations

def get_img_bboxess(annotations):
    # i = np.random.randint(0, len(annotations))
    for i in tqdm(range(len(annotations))):
        anno = annotations[i].strip().split(' ')
        img_path = anno[0]
        bboxes = np.array([list(map(float, box.split(','))) for box in anno[1:]])
        img = cv2.imread(img_path)
        if img is None:
            file_name = os.path.basename(img_path).split('.')[0]
            xml_path = 'D:\python\Aclass\myself_V4\dataset\Annotations\\' + file_name + '.xml'
            if os.path.exists(xml_path):
                os.remove(xml_path)
                print('remove %s'%xml_path)
            else:
                print('no such file:%s'%xml_path)
        if bboxes==[]:
            file_name = os.path.basename(img_path).split('.')[0]
            xml_path = 'D:\python\Aclass\myself_V4\dataset\Annotations\\' + file_name + '.xml'
            if os.path.exists(img_path):
                os.remove(img_path)
                os.remove(xml_path)
                print('remove %s' % path)
            else:
                print('no such file:%s' % path)

if __name__ == '__main__':
    sets = ['val_annotation.txt','train_annotation.txt','test_annotation.txt']
    for i in sets:
        path = '/data\\'
        path = path+i
        annotations = load_annotations(path)
        get_img_bboxess(annotations)